package com.appspot.dojompdft.server;

import java.util.Date;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.Query;

import com.appspot.dojompdft.client.EventoServico;
import com.appspot.dojompdft.client.InscricaoServico;
import com.appspot.dojompdft.shared.Evento;
import com.appspot.dojompdft.shared.Inscricao;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

@SuppressWarnings("serial")
public class InscricaoServicoImpl extends RemoteServiceServlet implements InscricaoServico {

	@Override
	public String desistir(String eventoId, String nome) throws RuntimeException {
		EntityManager em = EMF.get().createEntityManager();
		EntityTransaction tx = em.getTransaction();

		EventoServico eventoServico = new EventoServicoImpl();
		Evento evento = eventoServico.obterPelaChave(eventoId);
		
		try {
			Query q = em.createQuery("SELECT FROM Inscricao WHERE nome = :nome AND evento = :evento");
			q.setParameter("nome", nome);
			q.setParameter("evento", evento);
			q.setMaxResults(1);

			List<Inscricao> lista = q.getResultList();

			if (lista != null && lista.size() > 0) {
				tx.begin();
				Inscricao i = lista.get(0);
				lista = null;
				em.remove(i);
				tx.commit();
			} 
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (tx.isActive())
				tx.rollback();
			em.close();
		}
		
		return eventoId;
	}

	@Override
	public String inscrever(String eventoId, String nome) throws RuntimeException {
		
		EntityManager em = EMF.get().createEntityManager();
		EntityTransaction tx = em.getTransaction();
		
		EventoServico eventoServico = new EventoServicoImpl();
		Evento evento = eventoServico.obterPelaChave(eventoId);
		
		List<Inscricao> registros = em.createQuery("SELECT FROM Inscricao WHERE nome = :nome and evento = :evento")
		.setParameter("nome", nome).setParameter("evento", evento).getResultList();

		if (registros != null && registros.size() == 0) { 
			try {
				tx.begin();
				
				Inscricao inscricao = new Inscricao();
				inscricao.setNome(nome);
				inscricao.setDataInscricao(new Date());
				inscricao.setEvento(evento);
				em.persist(inscricao);
				
				tx.commit();
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				if (tx.isActive())
					tx.rollback();
				em.close();
			}
		} 
		
		return eventoId;
		
	}

	@Override
	public Inscricao salvar(Inscricao inscricao) {
		EntityManager em = EMF.get().createEntityManager();
		EntityTransaction tx = em.getTransaction();
		
		try {
			tx.begin();
			em.persist(inscricao);
			
			if (tx.isActive())
				tx.commit();
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		} finally {
			if (tx.isActive())
				tx.rollback();
			em.close();
		}
		
		return inscricao;
	}

}
